package pl.edu.agh.uhm.core;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.part.ViewPart;

import pl.edu.agh.uhm.core.model.DevicesContentProvider;
import pl.edu.agh.uhm.core.model.DevicesLabelProvider;
import pl.edu.agh.uhm.core.model.StubHypervisor;
import pl.edu.agh.uhm.discoverer.Hypervisor;
import pl.edu.agh.uhm.discoverer.VirtualMachine;


public class DevicesTreeView extends ViewPart{


	public static String ID="pl.edu.agh.uhm.core.DevicesTreeView";
	
	public static List<Hypervisor> root=new ArrayList<Hypervisor>();
	public static List<VirtualMachine> vms=new ArrayList<VirtualMachine>();
	
	
	private TreeViewer treeViewer;
	private DevicesListener hypervisorsManager=new DevicesListener(this);
	

	
	@Override
	public void createPartControl(Composite parent) {
		
		
		
		treeViewer = new TreeViewer(parent,SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
		treeViewer.setContentProvider(new DevicesContentProvider());
		treeViewer.setLabelProvider(new DevicesLabelProvider());
		treeViewer.setInput(getInitialInput());
		treeViewer.expandAll();	
		hypervisorsManager.init();
		hypervisorsManager.getAllHypervisors();
		hypervisorsManager.getAllVMs();
	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub
		
	}

	public void dispose(){
		
		super.dispose();
	
	}
	
	
	private Object getInitialInput(){
		
		
		return root;
		
	}

	public void addHypervisor(Hypervisor hypervisor) {
	
		System.out.println("adding hypervisor to the tree!");
		root.add(hypervisor);	
		refreshWithNewThread();
	
	}
	
	public void addVirtualMachine(VirtualMachine virtualMachine) {
		
		System.out.println("adding hypervisor to the tree!");
		vms.add(virtualMachine);	
		refreshWithNewThread();
	
	}
	
	private void refreshWithNewThread() {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
			if (treeViewer != null)
				treeViewer.refresh();
			}});
		
	}

	

	public void deleteHypervisor() {
		
	}
	
	
	
}
